package com.gxstnu.service;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxstnu.entity.Admin;
import com.gxstnu.exception.CustomerException;
import com.gxstnu.mapper.AdminMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AdminService {

    @Resource
    AdminMapper adminMapper;

    public void add(Admin admin) {
        // 根据新的账号查询数据库  是否存在同样账号的数据
        Admin dbAdmin = adminMapper.selectByUsername(admin.getUsername());
        if (dbAdmin != null) {
            throw new CustomerException("账号重复");
        }
        // 默认密码
        if (StrUtil.isBlank(admin.getPassword())) {
            admin.setPassword("admin");
        }
        adminMapper.insert(admin);
    }

    public List<Admin> selectAll(Admin admin){
            return adminMapper.selectAll(admin);
    }

    public PageInfo<Admin> selectPage(Integer pageNum, Integer pageSize,Admin admin ) {
        //开启分页查询
        PageHelper.startPage(pageNum,pageSize);
        List<Admin> list = adminMapper.selectAll(admin);
        return PageInfo.of(list);
    }

    public void update(Admin admin) {
        adminMapper.updateById(admin);

    }

    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    public void deleteBatch(List<Admin> list) {
        for (Admin admin : list) {
            deleteById(admin.getId());
        }
    }

    public Admin login(Admin admin) {
        //验证账号是否存在
        Admin dbadmin = adminMapper.selectByUsername(admin.getUsername());
        if(dbadmin == null)
            throw new CustomerException("账号不存在");
        //验证密码是否正确
        if(!dbadmin.getPassword().equals(admin.getPassword()))
            throw new CustomerException("密码错误");
            
        // 生成token (使用用户名和时间戳组合)
        String token = admin.getUsername() + "_" + System.currentTimeMillis();
        dbadmin.setToken(token);
        
        return dbadmin;
    }
}
